﻿@using WishlistUtilities;
@{
	PageData["Title"] = "Manage Lists";

	WebSecurity.RequireAuthenticatedUser();

	var db = Database.Open("wishlistdb");
	var currentUser = db.QuerySingle("SELECT Username, DefaultListId FROM WishlistUser WHERE Id = @0", WebSecurity.CurrentUserId);
}
<h1>Manage Lists</h1>
@{
	if (IsPost) {
		if (!Request["action"].IsEmpty()) {
            //If user would like to delete the list, ensure that the list belongs to that user and then perform the delete
			if (Request["action"] == "delete" && !Request["deleteListId"].IsEmpty()) {
				
                var usersList = db.QuerySingle("SELECT WishlistUserId FROM List WHERE Id = @0", Request["deleteListId"]);
				if (usersList.WishlistUserId == WebSecurity.CurrentUserId) {
					if (currentUser.DefaultListId != Request["deleteListId"].AsInt()) {
                        try {
						    db.Execute("DELETE FROM List WHERE Id = @0", Request["deleteListId"]);
                        } catch (Exception) {
                            Response.Redirect("~/Shared/Errors/Error");
				        }
					} else {
						//User would only hit this if they injected their ID into the form to try to delete their default list
                        Response.Redirect("~/Shared/Errors/Error");

					}
				} else {
					//User is injecting form data and attempting to delete another users' list
					Response.Redirect("~/Shared/Errors/Error");
				}
			}
            //If users would like to make the list his or her default, ensure ownership before, then perform the update
			if (Request["action"] == "makeDefault" && !Request["defaultListId"].IsEmpty()) {
                var usersList = db.QuerySingle("SELECT WishlistUserId FROM List WHERE Id = @0", Request["defaultListId"]);
				if (usersList.WishlistUserId == WebSecurity.CurrentUserId) {
                    try {
    				    db.Execute("UPDATE WishlistUser SET DefaultListID = @0 WHERE Id = @1", Request["defaultListId"], WebSecurity.CurrentUserId);
                    } catch (Exception) {
					    Response.Redirect("~/Shared/Errors/Error");
				    }
                    currentUser = db.QuerySingle("SELECT Username, DefaultListId FROM WishlistUser WHERE Id = @0", WebSecurity.CurrentUserId);
				} else {
					//User is injecting form data and attempting to update another users' list
					Response.Redirect("~/Shared/Errors/Error");
				}
			}
		} else {
			Response.Redirect("~/Shared/Errors/Error");
		}
	}
    
    var listQuery = db.Query("SELECT * FROM List WHERE WishlistUserId = @0", WebSecurity.CurrentUserId);
}
<div>
    @if(Freemium.IsFeatureEnabledForCurrentUser("Create Lists"))
    {
        <p>
            <a href="CreateList">Create List</a>
        </p>
    }
    <h2>Your existing lists:</h2>
    <script type="text/javascript">
	    function deleteList(listId) {
		    $("#DeleteConfirmationDialog" + listId).dialog(
			    {
				    resizable: false, height: 250, width: 300, modal: true, closeOnEscape: true, draggable: false,
				    buttons: {
					    'Cancel': function() {
						    $(this).dialog("close");
					     },
					    'OK': function() {
						    document.forms['deleteListForm'+listId].submit();
					    }
				    }
			    }
		    );
	    }
	    function defaultList(listId) {
		    document.forms['defaultListForm'+listId].submit();
	    }
        //Show JS Links if user has JS enabled
        $(document).ready(function() {
            $(".scriptsubmit").toggle();
            $(".noscriptsubmit").toggle();
        });
    </script>
    <ul>
    @{
        //For each list, display UI that allows you to edit, delete, or make it the default list
	    foreach (var list in listQuery) {
		    var sluggedListName = SlugUtility.CreateSlug(list.Name);
		    var sluggedUserName = SlugUtility.CreateSlug(currentUser.Username);
		    <li>
                <a href="@("EditList/" + list.Id)"><img src="@Href("~/Content/Images/icon-edit.png")" class="imageLink"/>Edit</a> -
			    <a href="@("DisplayList/" + sluggedUserName + "/" + sluggedListName)">@list.Name</a> -
			    @if (list.Id == currentUser.DefaultListId) {
				    <span class="info">Default</span>
                    <br/>@list.Description
			    } else {
				    <text>
					    <a class="scriptsubmit" href="javascript:defaultList(@(list.Id))">Make Default</a> -
					    <a class="scriptsubmit" href="javascript:deleteList(@(list.Id))">[x]</a>
				    </text>
			        <br/>@list.Description
                    <div id="DeleteConfirmationDialog@(list.Id)" class="jquery-dialog" title="Delete List">
			            <span class="ui-icon ui-icon-alert ui-icon-float"></span>
	                    <p>Are you sure you want to delete @list.Name?</p>
		            </div>
                    <form id="defaultListForm@(list.Id)" method="post" action="">
                        <input type="submit" class="noscriptsubmit" value="Make Default"/>
				        <input type="hidden" name="action" value="makeDefault"/>
				        <input type="hidden" name="defaultListId" value="@list.Id"/>
			        </form>
			        <form id="deleteListForm@(list.Id)" method="post" action="">
                        <input type="submit" class="noscriptsubmit" value="Delete"/>
				        <input type="hidden" name="action" value="delete"/>
				        <input type="hidden" name="deleteListId" value="@list.Id"/>
			        </form>
			    }
		    </li>
	    }
    }
    </ul>
</div>

